<?php
/**
 * nns_cms_global 表
 * 
 * @author Wuhao
 * @version SVN: <svn_id>
 */

// 公共函数库 在 nn_logic 目录下
include_once dirname(dirname(__FILE__)) . '/nl_common.func.php';
/**
 * 不用缓存
 * 
 * @package nl_global
 */

class nl_global
{
    /**
     * 数据库名字
     */
    const DB_NAME    = 'nns_cms_global';

    const NNS_ID     = 'nns_id';
    const NNS_MODULE = 'nns_module';
    const NNS_KEY    = 'nns_key';
    const NNS_VALUE  = 'nns_value';
/*****************************************************************************/
    /**
     * 通过条件数组取global
     * 
     * @access public
     * @param object $dc nl_dc的实例，传入前保证已调用了$dc->open();
     * @param array $conditionData 一个关联的条件数组
     * @throws exception
     * @return boolean|array
     */
    public static function get_global_by_conditions($dc, $conditionData)
    {
        self::_checkDc($dc);
        if (!is_array($conditionData)) {
            throw new Exception(__METHOD__ . ' 第2个参数必须是个关联数组');
        }
        // 条件允许nns_id和nns_module两个字段
        $dataKeys  = array(self::NNS_ID, self::NNS_MODULE, self::NNS_KEY);
        $whereStmt = array();
        $limit     = $order = '';
        foreach ($conditionData as $key => $val) {
            if (in_array($key, $dataKeys)) {
                $whereStmt[] = "`$key`='$val'";
            // 使用limit1 和 limit2 来指定 LIMIT的2个参数
            } elseif (isset($conditionData['limit1'])) {
                $limit = " LIMIT {$conditionData['limit1']}";
                if (isset($conditionData['limit2'])) {
                    $limit .= ",{$conditionData['limit2']}";
                }
            // 使用orderCol 和 orderPolicy 来指定排序列和升降序
            } elseif (isset($conditionData['orderCol'])) {
                $order = " ORDER BY {$conditionData['orderCol']}";
                if (isset($conditionData['orderPolicy'])) {
                    $order .= " {$conditionData['orderPolicy']}";
                }
            }
        }
        $whereStmt = implode(' AND ', $whereStmt);
        $sql       = 'SELECT * FROM `' . self::DB_NAME .
                     "` WHERE {$whereStmt}{$limit}{$order}";
                     
        return nl_query_by_db($sql, $dc->db());
        
    }
    /**
     * 根据条件取总数
     * 
     * @access public
     * @param object $dc nl_dc的实例，传入前保证已调用了$dc->open();
     * @param array $conditionData 一个关联的条件数组
     * @throws exception
     * @return boolean|array
     */
    public static function count_global_by_conditions($dc, $conditionData)
    {
        self::_checkDc($dc);
        if (!is_array($conditionData)) {
            throw new Exception(__METHOD__ . ' 第2个参数必须是个关联数组');
        }
        $dataKeys  = array(self::NNS_MODULE, self::NNS_KEY);
        $whereStmt = array();
        foreach ($conditionData as $key => $val) {
            if (in_array($key, $dataKeys)) {
                $whereStmt[] = "`$key`='$val'";
            }
        }
        $whereStmt = implode(' AND ', $whereStmt);
        $sql       = 'SELECT COUNT(1) AS `rowCount` FROM `' . self::DB_NAME .
                     "` WHERE {$whereStmt}";
                     
        return nl_query_by_db($sql, $dc->db());
    }
/*****************************************************************************/
    /**
     * 新增global
     * 
     * @access public
     * @param object $dc nl_dc的实例，传入前保证已调用了$dc->open();
     * @param array $addData 一个关联数组，包含了表的各字段值，当然还有id。可用KEY 请见下方的 $dataKeys
     * @throws exception
     * @return boolean
     */
    public static function add_global($dc, $addData)
    {
        self::_checkDc($dc);
        if (!is_array($addData)) {
            throw new Exception(__METHOD__ . ' 第2个参数必须是关联数组');
        }
        // 过滤参数
        $dataKeys = array(self::NNS_ID, self::NNS_MODULE, self::NNS_KEY, self::NNS_VALUE);
        $values   = array();
        foreach ($addData as $key => $val) {
            if (in_array($key, $dataKeys)) {
                $values[] = "'$val'";
            } else {
                throw new Exception(__METHOD__ . "字段值不合法: {$key}");
                exit(1);
            }
        }
        $values = implode(',', $values);
        $keys   = implode('`,`', $dataKeys);
        $sql    = 'INSERT INTO `' . self::DB_NAME .
                  "` (`{$keys}`) VALUES ($values)";
        return nl_execute_by_db($sql, $dc->db());
    }
/*****************************************************************************/
    /**
     * 通过nns_id修改global
     * 
     * @access public
     * @param object $dc nl_dc的实例，传入前保证已调用了$dc->open();
     * @param string $id 32的guid
     * @param array $modifyData 包含要修改的值的关联数组
     * @throws exception
     * @return boolean
     */
    public static function modify_global_by_id($dc, $id, $modifyData)
    {
        self::_checkDc($dc);
        if (!is_array($modifyData)) {
            throw new Exception(__METHOD__ . ' 第3个参数必须是关联数组');
        }
        $setStmt  = array();
        // 例行过滤参数，可能后续增加其他字段
        $dataKeys = array(self::NNS_VALUE);
        foreach ($modifyData as $key => $val) {
            if (in_array($key, $dataKeys)) {
                $setStmt[] = "`$key`='$val'";
            }
        }
        $setStmt = implode(',', $setStmt);
        $sql = 'UPDATE `' . self::DB_NAME . "` SET $setStmt WHERE `" . self::NNS_ID . "`='{$id}'";
        return nl_execute_by_db($sql, $dc->db());
    }
/*****************************************************************************/
    /**
     * 通过多个ID删除GLOBAL
     * 
     * @access public
     * @param object $dc nl_dc的实例，传入前保证已调用了$dc->open();
     * @param array $ids 包含一个或多个ID的数组
     * @throws exception
     * @return boolean
     */
    public static function delete_global_by_ids($dc, $ids)
    {
        self::_checkDc($dc);
        if (!is_array($ids)) {
            throw new Exception(__METHOD__ . ' 第2个参数必须是关联数组');
        }
        $ids = implode('","', $ids);
        $sql = 'DELETE FROM `' . self::DB_NAME . "` WHERE `nns_id` IN (\"$ids\")";
        return nl_execute_by_db($sql, $dc->db());
    }
/*****************************************************************************/
    /**
     * 通过KEY来删除GLOBAL
     * 
     * @access public
     * @param mixed $dc
     * @param mixed $key nns_key字段
     * @return boolean
     */
    public static function delete_global_by_key($dc, $key) {
        self::_checkDc($dc);
        $sql = 'DELETE FROM `' . self::DB_NAME . "` WHERE `nns_key`='{$key}'";
        return nl_execute_by_db($sql, $dc->db());
    }
/*****************************************************************************/
    /**
     * 检查DC是否合法
     * 
     * @access private
     * @param mixed $dc 要检查的$dc 实例
     * @return void
     * @throws exception
     */
    private static function _checkDc($dc)
    {
        if (!$dc instanceof nl_dc ||
            !$dc->is_db_open()) {
            throw new Exception('参数 DC 不正确，或者没有调用 open()');
        }
    }
    
    
/****************将原来的common/global.class.php方法移动到这里****************/
/**
 * 获取所有的配置模块
 */
    static public function get_module($dc){
        if(empty($dc)){
            return false;
        }
        $db=$dc->db();
        $sql="select nns_module from nns_cms_global group by nns_module";
        $result=nl_query_by_db($sql,$db);
        if(is_array($result)){
            $i=0;
            foreach($result as $item){
                $res[$i]=$item['nns_module'];	
                $i++;
            }
            $result=$res;	
        }		
        return $result;
    }
    
/**
 * @param DC $dc模块
 * @param string $module模块类型
 * @return array(配置列表结果
 * (
 * "audit"=>自动审核
 * "sen_word"=>敏感词汇集以“，”分割
 * )
 * )
 * 失败返回			   false
 * 成功结果集为空返回   true  
 */
    
   static public function get_global($dc,$module) {
        if(empty($dc)||empty($module)){
            return false;
        }
        $db=$dc->db();
        $sql="select * from nns_cms_global where nns_module='$module'";
        $result=nl_query_by_db($sql,$db);
        if(is_array($result)){
            foreach($result as $item){
               $data[$item['nns_key']]=$item['nns_value'];
            }
            return $data;
        }
        
        return $result; 	
    }
    
    /**
     * @param DC $dc模块
     * @param string $module 模块类型
     * @param string $key  参数键
     * @param string $value 参数值
     * @return 
     * 成功返回true 
     * 失败返回false
     */
    static public function modify_global($dc,$module,$key,$value){
        if(empty($dc)){
            return false;
        }
        if(empty($module)||empty($key)){
            return false;
        }
        $db=$dc->db();
        $key=trim($key);
        $value=trim($value);
        $sql='select nns_id from nns_cms_global where nns_module='."'$module'".'and nns_key='."'$key'";
        $result=nl_query_by_db($sql,$db);
        if($result==false){
            return false;
        }elseif(is_array($result)){
            $sql="update nns_cms_global set nns_value='$value' where nns_module='$module' and nns_key='$key'";
            $result=nl_execute_by_db($sql,$db);	
        }else{
            $nns_id = np_guid_rand();
            $sql="insert into nns_cms_global (nns_id,nns_module,nns_key,nns_value) values ('$nns_id','$module','$key','$value')";
            $result=nl_execute_by_db($sql,$db);
        }
        return $result;
        
    }
    
    /**
     * 添加开机EPG默认出参
     * @param array(
     * 		'paket_type'=>包类型
     * 		'paket_id'=>包ID,
     * 		'category_id'=>栏目ID,
     * 		'category_name'=>栏目名称，
     * )
     * @param TRUE
     * 			false
     */
    
    static public function add_init_epg_params($dc,$params){
        $sql='insert into nns_init_params_item ( ' .
            'nns_id,'.
            'nns_init_type,' .
            'nns_packet_type,'.
            'nns_packet_id,'.
            'nns_category_id,'.
            'nns_category_name ' .
            ')values(' .
            '\''.np_guid_rand().'\','.
            '\'packet\','.
            '\''.$params['packet_type'].'\','.
            '\''.$params['packet_id'].'\','.
            '\''.$params['category_id'].'\','.
            '\''.$params['category_name'].'\'' .
            ')';
            
            $result=nl_execute_by_db($sql,$dc->db());
            
        return $result;
    }
    /**
     * 修改EPG默认出参
     * @param id 
     * @param array(
     * 		'tag'=>EPG标识
     * 		'action_type'=>行为参数,
     * 		'group'=>分组参数,
     * )
     * @param TRUE
     * 			false
     */
    static public function modify_init_epg_params($dc,$id,$params){
        $sql='update nns_init_params_item  set ' .
            'nns_tag=\''.$params['tag'].'\','.
            'nns_action_type=\''.$params['action_type'].'\','.
            'nns_group=\''.$params['group'].'\' '.
            'where nns_id=\''.$id.'\'' ;
//    		echo $sql;die;
            $result=nl_execute_by_db($sql,$dc->db());
            
        return $result;
    }
   /**
    * @param array(
    * 		"tag"=>EPG标识
    * 		"action_type"=>行为参数
    * 		"group"=>分组参数
    * 	)
    * @return
    */ 
    static public function get_init_epg_params($dc,$params=NULL){
        $sql='select * from nns_init_params_item ' ;
        if (is_array($params)){
            $sql_ex = '';
            foreach ($params as $key=>$param){
                if ($key=='tag'){
                    $sql_ex.='and (nns_tag=\'\' or ' .
                    'ISNULL(nns_tag) or ' .
                    'LOCATE(\','.$param.',\',CONCAT(\',\',nns_tag))>0) ';
                }else{
                    $sql_ex.= 'and nns_'.$key.'=\''.$param.'\' ';
                }
            }
            //-->start xingcheng.hu 去掉where1=1
            if(!empty($sql_ex))
            {
                $sql .= 'where ';
                $sql_ex = ltrim($sql_ex,'');
                $sql_ex = ltrim($sql_ex,'and');
                $sql .= $sql_ex;
            }
            //<--end
        }
        $result=nl_query_by_db($sql,$dc->db());
            
        return $result;
    }
    static public function delete_init_epg_params($dc,$id){
        $sql='delete from nns_init_params_item where nns_id=\''.$id.'\'' ;
            
        $result=nl_execute_by_db($sql,$dc->db());
            
        return $result;
    }
}